﻿using System;
using System.IO;
using blackhouse.WebNemo.Data;

namespace blackhouse.WebNemo.Business.Files
{

    public interface INemoFile
    {
        int BelongsToGroupId { get; }
        string BelongsToGroupName { get; }
        int StoredInColumnId { get; }
        string StoredInColumnName { get; }
        int BelongToRecord { get; }
        string Name { get; }
        Guid Guid { get; }
        DateTime LastModified { get; }

        Stream GetStream();

    }

    internal class NemoFile : INemoFile
    {
        #region Fields

        private readonly IDataAccess dataLayer;
        private readonly int belongsToGroupId;
        private readonly string belongsToGroupName;
        private readonly int storedInColumnId;
        private readonly string storedInColumnName;
        private readonly int belongToRecord;
        private readonly string name;
        private readonly Guid guid;
        private readonly DateTime lastModified;

        #endregion

        #region Properties

        public int BelongsToGroupId {
            get { return this.belongsToGroupId; }
        }

        public string BelongsToGroupName {
            get { return this.belongsToGroupName; }
        }

        public int StoredInColumnId {
            get { return this.storedInColumnId; }
        }

        public string StoredInColumnName {
            get { return this.storedInColumnName; }
        }

        public int BelongToRecord {
            get { return this.belongToRecord; }
        }

        public string Name {
            get { return this.name; }
        }

        public Guid Guid {
            get { return this.guid; }
        }

        public DateTime LastModified {
            get { return this.lastModified; }
        }

        #endregion

        #region Constructors

        public NemoFile(IDataAccess dataAccess, FileInfoData fileInfo) {
            this.dataLayer = dataAccess;
            this.belongsToGroupId = fileInfo.GroupId;
            this.belongsToGroupName = fileInfo.GroupName;
            this.storedInColumnId = fileInfo.ColumnId;
            this.storedInColumnName = fileInfo.ColumnName;
            this.belongToRecord = fileInfo.RecordId;
            this.name = fileInfo.FileName;
            this.guid = fileInfo.FileGuid;
            this.lastModified = fileInfo.LastModified;
        }

        #endregion

        #region Methods

        public Stream GetStream() {
            var data = this.dataLayer.GetFileStream(this.StoredInColumnName, this.BelongsToGroupName, this.BelongToRecord);
            var stream = new MemoryStream(data.Length);
            using (var writer = new BinaryWriter(stream)) {
                writer.Write(data);
            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

        #endregion

    }
}
